import DeviceTemplate from "@/components/DeviceTemplate";
import React, { useState } from 'react';
import { Image, StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import { useNavigation } from 'expo-router';
import { useAudioPlayer } from 'expo-audio';
import DynamometerParser from '../../utils/DynamometerParser';

const DynamometerDevice: React.FC = () => {
    const [showCompletionDialog, setShowCompletionDialog] = useState(false);
    const navigation = useNavigation();
    
    // 使用 useAudioPlayer hook 创建音频播放器
    const audioSource = require('../../assets/mp3/notice.mp3');
    const player = useAudioPlayer(audioSource);

    const playNotificationSound = () => {
        try {
            // 重置到开头并播放
            player.seekTo(0);
            player.play();
        } catch (error) {
            console.error('Error playing sound:', error);
        }
    };

    // 判断握力检测是否完成
    const isDynamometerTestComplete = (measurement: any): boolean => {
        if (!measurement || typeof measurement.value !== 'string') return false;
        // 握力检测完成条件：基于报文中的完成标志位
        // 如果解析结果中包含isComplete标志且为true，表示检测完成
        if (measurement.isComplete === true) {
            return true;
        }
        // 兜底条件：有有效的握力值
        const value = parseFloat(measurement.value);
        return !isNaN(value) && value > 0;
    };

    const handleTestComplete = () => {
        // 显示检测完成提示对话框
        setShowCompletionDialog(true);
        // 播放完成提示音
        playNotificationSound();
    };

    const finishTest = () => {
        setShowCompletionDialog(false);
        navigation.goBack();
    };

    const GuideImageComponent = () => (
        <View style={styles.imageContainer}>
            <Image
                source={require('../../assets/images/dynamometer.jpg')}
                style={styles.image}
                resizeMode="stretch"
            />
        </View>
    );

    const GuideTextComponent = ({ type }: { type?: string }) => (
        <View style={styles.guideTextContainer}>
            <Text style={styles.guideTitle}>握力检测操作指南</Text>
            <Text style={styles.guideStep}>1. 打开握力设备，等待状态变为已连接</Text>
            <Text style={styles.guideStep}>2. 调整握力计位置，使其舒适地握在手中</Text>
            <Text style={styles.guideStep}>3. 点击"开始检测"按键</Text>
            <Text style={styles.guideStep}>4. 请用右手（左撇子用左手）尽最大力量握紧握力计，然后放松，系统自动记录最大握力</Text>
            <Text style={styles.guideStep}>5. 测试完成后长按开关键关闭握力设备</Text>
        </View>
    );

    return (
        <>
            <DeviceTemplate
                deviceName="握力检测仪"
                deviceNamePrefix="YDL"
                serviceUUID={DynamometerParser.SERVICE_UUID.toLowerCase()}
                dataCharacteristic={DynamometerParser.DATA_CHARACTERISTIC.toLowerCase()}
                commandServiceUUID={DynamometerParser.COMMAND_SERVICE.toLowerCase()}
                commandCharacteristic={DynamometerParser.COMMAND_CHARACTERISTIC.toLowerCase()}
                startCommand={DynamometerParser.START_COMMAND}
                withResp={true}
                stopCommand={DynamometerParser.STOP_COMMAND}
                initCommands={DynamometerParser.INIT_COMMANDS}
                parser={{
                    parseData: DynamometerParser.parseData,
                }}
                deviceRoute="Dynamometer"
                onTestComplete={handleTestComplete}
            >
                <GuideTextComponent type="guideText"/>
                <GuideImageComponent/>
            </DeviceTemplate>
            
            {/* 检测完成提示对话框 */}
            {showCompletionDialog && (
                <View style={styles.dialogOverlay}>
                    <View style={styles.dialogContainer}>
                        <Text style={styles.dialogTitle}>检测完成</Text>
                        <Text style={styles.dialogMessage}>您的检测已完成并已自动保存结果</Text>
                        <View style={styles.dialogButtons}>
                            <TouchableOpacity
                                style={[styles.dialogButton, styles.stayButton]}
                                onPress={() => {
                                    // 重置检测完成状态，允许下次继续检测
                                    setShowCompletionDialog(false);
                                }}
                            >
                                <Text style={styles.stayButtonText}>继续检测</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[styles.dialogButton, styles.returnButton]}
                                onPress={finishTest}
                            >
                                <Text style={styles.returnButtonText}>返回</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            )}
        </>
    );
};

const styles = StyleSheet.create({
    imageContainer: {
        width: '100%',
        alignItems: 'center',
        marginBottom: 15,
    },
    image: {
        width: '100%',
        height: 300,
        backgroundColor: 'black',
        borderRadius: 8,
    },
    guideTextContainer: {
        width: '100%',
        padding: 10,
    },
    guideTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#0a7ea4',
        marginBottom: 15,
        textAlign: 'center',
    },
    guideStep: {
        fontSize: 14,
        color: '#333',
        marginBottom: 8,
        lineHeight: 20,
    },
    guideTip: {
        fontSize: 14,
        color: '#0a7ea4',
        fontStyle: 'italic',
        marginTop: 10,
    },
    // 检测完成提示对话框样式
    dialogOverlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 1000,
    },
    dialogContainer: {
        backgroundColor: 'white',
        borderRadius: 12,
        padding: 24,
        width: '80%',
        maxWidth: 320,
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5,
    },
    dialogTitle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 16,
    },
    dialogMessage: {
        fontSize: 16,
        color: '#666',
        textAlign: 'center',
        marginBottom: 24,
    },
    dialogButtons: {
        flexDirection: 'row',
        width: '100%',
        justifyContent: 'space-between',
    },
    dialogButton: {
        flex: 1,
        paddingVertical: 12,
        paddingHorizontal: 16,
        borderRadius: 8,
        alignItems: 'center',
        marginHorizontal: 8,
    },
    stayButton: {
        backgroundColor: '#f0f0f0',
    },
    returnButton: {
        backgroundColor: '#0a7ea4',
    },
    stayButtonText: {
        fontSize: 16,
        color: '#333',
        fontWeight: 'bold',
    },
    returnButtonText: {
        fontSize: 16,
        color: 'white',
        fontWeight: 'bold',
    }
});

export default DynamometerDevice;
